##########################################
## Copyright 2012-2013 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

from PyQt4 import QtCore
from lisp.core.media import Media


class Collector(QtCore.QObject):

    onMediaAdded = QtCore.pyqtSignal(object)
    onMediaRemoved = QtCore.pyqtSignal(object)

    def __init__(self):
        super(Collector, self).__init__()
        self.media = []

    def addMedia(self, media):
        self.media.append(media)

        media.onPlay.connect(self.stopAll)
        media.onPlay.connect(self.startGroups)
        media.onPause.connect(self.pauseGroups)
        media.onStop.connect(self.stopGroups)

        self.onMediaAdded.emit(media)

    def removeMedia(self, media):
        if(media is not None):
            media.interrupt(False)
            self.media.remove(media)
            self.onMediaRemoved.emit(media)
        elif(None in media):
            self.media.remove(None)

    def resetCollector(self):
        for media in self.media:
            self.removeMedia(media)

    def stopAll(self, media):
        if(media.conf['stopAll']):
            for m in self.media:
                if(m != media and m.state != Media.NONE):
                    m.stop()

    def pauseGroups(self, media):
        if(media.conf['groups'] != []):
            groups = media.conf['groups']
            for media in self.media:
                if(media.state != Media.PLAYING):
                    continue
                for group in groups:
                    if(group in media.conf['groups']):
                        media.pause()
                        break

    def stopGroups(self, media):
        if(media.conf['groups'] != []):
            groups = media.conf['groups']
            for media in self.media:
                if(media.state != Media.PLAYING and media.state != Media.PAUSED):
                    continue
                for group in groups:
                    if(group in media.conf['groups']):
                        media.stop()
                        break

    def startGroups(self, media):
        if(media.conf['groups'] != []):
            groups = media.conf['groups']
            for media in self.media:
                if(media.state != Media.STOPPED and media.state != Media.PAUSED):
                    continue
                for group in groups:
                    if(group in media.conf['groups']):
                        media.play()
                        break
